package gui;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import remoteService.RemoteCourseOpPanel;
import remoteService.RemoteLoginUI;

import concole.IOHelper;
import concole.Student;

public class StudentBorad extends OperatingBoard {
	ArrayList<JButton> operationButtons = new ArrayList<JButton>();
	ArrayList<JPanel> operatingPanels = new ArrayList<JPanel>();
	protected CourseOpPanel opSelect;
	protected CourseOpPanel opPanel2;
	protected Student user;

	public StudentBorad() {

	}

	public StudentBorad(String ID, int identity) {
		super(ID, identity);
		this.ID = ID;
		this.setRemote();
		this.userName = getNameFromFile();
		infoLabel.setText("             Welcome " + " " + userName + " !");
		/* to create specific operationButtons */
		BoxLayout yLayout = new BoxLayout(operationListPanel, BoxLayout.Y_AXIS);
		operationListPanel.setLayout(yLayout);
		JButton showListButton = new JButton(" Show CourseList   ");
		showListButton.setSize(50, 200);
		showListButton.setFont(middlFont);
		operationListPanel.add(showListButton);
		operationButtons.add(showListButton);
		JButton selectCourseBt = new JButton(" Select   Course      ");
		selectCourseBt.setSize(50, 200);
		selectCourseBt.setFont(middlFont);
		operationListPanel.add(selectCourseBt);
		operationButtons.add(selectCourseBt);
		JButton quitBt = new JButton(" Quit      Course      ");
		quitBt.setSize(50, 200);
		quitBt.setFont(middlFont);
		operationListPanel.add(quitBt);
		operationButtons.add(quitBt);
		JButton showScoreBt = new JButton(" Show     Score        ");
		showScoreBt.setSize(50, 200);
		showScoreBt.setFont(middlFont);
		operationListPanel.add(showScoreBt);
		operationButtons.add(showScoreBt);
		JButton exitButton = new JButton("---------Exit--------- ");
		exitButton.setSize(50, 200);
		exitButton.setFont(middlFont);
		exitButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				StudentBorad.this.setVisible(false);
				if (isRemote) {
					System.out.println("Exit to remoteLogin");
					new RemoteLoginUI();
				} else {
					System.out.println("Exit to localLogin");
					new LoginEntry();
				}
			}
		});
		operationListPanel.add(exitButton);

		for (JButton bt : operationButtons) {
			bt.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					// TODO Auto-generated method stub
					displayPanel(arg0);
				}
			});
		}
		/* create the match operation panel */

		// showCourseList
		JPanel showCoursePanel = new JPanel();
		showCoursePanel.setBounds(0, 0, 600, 500);
		showCoursePanel.setBackground(Color.orange);
		showCoursePanel.setLayout(new BorderLayout());
		String[][] tableDataStrings = { { "1", "1", "1", "1", "1", "1", "1",
				"1", "1" }, };
		String[] columnTitle = new String[] { "No.", "Name", "T's name",
				"T's num", "Elective", "Hours", "Credit", "StartWeek",
				"EndWeek", "Time", "Place", "Assist'Num" };
		final DefaultTableModel tableModel = new DefaultTableModel(
				tableDataStrings, columnTitle);

		final JTable jTable = new JTable(tableModel);
		jTable.setPreferredScrollableViewportSize(new Dimension(490, 400));
		jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		jTable.setBackground(Color.yellow);
		JScrollPane jScrollPane = new JScrollPane(jTable);
		jScrollPane.setBounds(20, 0, 550, 380);
		JButton showButton = new JButton(
				"-----------------------------Show courses---------------------------");
		showButton.setBounds(20, 390, 550, 40);
		showButton.setFont(middlFont);
		showButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				String[] allCourseStrings = showAllCourse(StudentBorad.this.ID);
				if (allCourseStrings == null) {
					JOptionPane.showMessageDialog(null,
							"You have not chosen any course uptil now");
					return;
				}
				tableModel.setRowCount(0);
				for (int i = 0; i < allCourseStrings.length; i++) {
					String[] arr = new String[12];
					arr = allCourseStrings[i].split(" ");
					System.out.println(arr[0] + "%" + arr[1] + "%" + arr[2]);
					tableModel.addRow(arr);
				}
				jTable.invalidate();
				jTable.updateUI();

			}
		});

		showCoursePanel.add(jScrollPane);
		showCoursePanel.add(showButton);
		operatingPanels.add(showCoursePanel);
		// Select Course
		JPanel selectPanel = new JPanel();
		selectPanel.setBounds(0, 0, 600, 500);
		selectPanel.setBackground(Color.green);
		selectPanel.setLayout(null);

		if (isRemote) {
			opSelect = new RemoteCourseOpPanel();
		} else {
			opSelect = new CourseOpPanel();
		}
		JButton selectBT = new JButton("Select");
		selectBT.setFont(middlFont);
		selectBT.setBounds(220, 300, 100, 30);
		selectBT.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String courseNumString = opSelect.getCourseNum();
				if (courseNumString.length() == 0) {
					JOptionPane.showMessageDialog(null,
							"Sorry the course number is needed");
					return;
				}
				boolean islearning = hasRight(courseNumString,
						StudentBorad.this.ID);
				if (islearning) {
					JOptionPane.showMessageDialog(null,
							"YOu have chosen the course");
					return;
				}
				selectCourse(courseNumString, StudentBorad.this.ID);
				JOptionPane.showMessageDialog(null, "Sucessfully select");
			}
		});

		selectPanel.add(opSelect);
		selectPanel.add(selectBT);
		operatingPanels.add(selectPanel);
		// quit course
		JPanel quitPanel = new JPanel();
		quitPanel.setBounds(0, 0, 600, 500);
		quitPanel.setBackground(Color.green);
		quitPanel.setLayout(null);
		if (isRemote) {
			opPanel2 = new RemoteCourseOpPanel();
		} else {
			opPanel2 = new CourseOpPanel();
		}
		JButton quitBT = new JButton("Quit");
		quitBT.setBounds(220, 300, 100, 30);
		quitBT.setFont(middlFont);
		quitBT.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub

				String courseNumString = opPanel2.getCourseNum();
				if (courseNumString.length() == 0) {
					JOptionPane.showMessageDialog(null,
							"Sorry the course number is needed");
					return;
				}
				boolean isLearning = hasRight(courseNumString,
						StudentBorad.this.ID);
				if (!isLearning) {
					JOptionPane.showMessageDialog(null,
							"YOu don't learn the ocurse");
					return;
				}
				quitCourse(courseNumString, StudentBorad.this.ID);
				JOptionPane.showMessageDialog(null,
						"Sucessfully Quit the course");
			}
		});

		quitPanel.add(opPanel2);
		quitPanel.add(quitBT);
		operatingPanels.add(quitPanel);

		// show score
		JPanel showScorePanel = new JPanel();
		showScorePanel.setBackground(Color.orange);
		showScorePanel.setBounds(0, 0, 600, 500);
		showScorePanel.setLayout(null);
		JLabel scoreCourseNumberLabel = new JLabel("Course Number");
		scoreCourseNumberLabel.setBounds(50, 50, 100, 30);
		final JTextField scoreCourseNumberFd = new JTextField();
		scoreCourseNumberFd.setFont(middlFont);
		scoreCourseNumberFd.setBounds(200, 50, 100, 30);
		JLabel scoreLb = new JLabel("Course score");
		scoreLb.setBounds(50, 100, 100, 30);
		final JTextField scoreFd = new JTextField();
		scoreFd.setBounds(200, 100, 100, 30);
		scoreFd.setFont(middlFont);
		JButton searchButton = new JButton("search");
		searchButton.setFont(middlFont);
		searchButton.setBounds(50, 150, 100, 30);
		searchButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				String courseNum = scoreCourseNumberFd.getText();
				if (courseNum.length() == 0) {
					JOptionPane
							.showMessageDialog(null, "courseNumber is null ");
					scoreFd.setText("");
					return;
				}
				if (!hasRight(courseNum, StudentBorad.this.ID)) {
					JOptionPane.showMessageDialog(null,
							"Sorry you don's select the course");
					scoreCourseNumberFd.setText("");
					scoreFd.setText("");
					return;
				}
				String scoreString = getScore(courseNum, StudentBorad.this.ID);
				if (scoreString == null) {
					JOptionPane.showMessageDialog(null,
							"Sorry the record not exist");
					scoreCourseNumberFd.setText("");
					scoreFd.setText("");
					return;
				}
				scoreFd.setText("");
				scoreFd.setText(scoreString);
			}
		});

		showScorePanel.add(scoreCourseNumberFd);
		showScorePanel.add(scoreCourseNumberLabel);
		showScorePanel.add(scoreFd);
		showScorePanel.add(scoreLb);
		showScorePanel.add(searchButton);
		operatingPanels.add(showScorePanel);

		/* make all display */
		this.repaint();
	}

	protected void setRemote() {
		this.isRemote = false;

	}

	protected String[] showAllCourse(String studentNumber) {
		// TODO Auto-generated method stub
		StringBuffer toShow = new StringBuffer();
		String allCourseString = IOHelper.findAllMatchInfo(1,
				"courseSelected.txt", studentNumber);
		if (allCourseString == null || allCourseString.length() == 0) {
			return null;
		}
		if (allCourseString.contains("\n")) {
			String[] allCourse = allCourseString.split("\n");

			for (int i = 0; i < allCourse.length; i++) {
				allCourse[i] = allCourse[i].substring(0,
						allCourse[i].indexOf(" "));
				allCourse[i] = allCourse[i].trim();
				toShow.append(IOHelper.findOneRecord(0, "courseList.txt",
						allCourse[i]));
				toShow.append("\n");
			}
			String toShowString = toShow.toString().trim();
			System.out.println(toShowString);
		} else {
			allCourseString = allCourseString.substring(0,
					allCourseString.indexOf(" "));
			allCourseString = allCourseString.trim();
			toShow.append(IOHelper.findOneRecord(0, "courseList.txt",
					allCourseString));
		}
		return toShow.toString().trim().split("\n");
	}

	protected void quitCourse(String courseNumString, String ID) {
		// TODO Auto-generated method stub
		IOHelper.deleteOneLine("courseSelected.txt", 0, courseNumString, 1,
				this.ID);
	}

	protected void selectCourse(String courseNumString, String ID) {
		// TODO Auto-generated method stub
		String toStoreString = courseNumString + " " + this.ID;
		IOHelper.addOneLine("courseSelected.txt", toStoreString);
	}

	protected String getScore(String courseNum, String ID) {
		// TODO Auto-generated method stub
		String resultString = "";
		resultString = IOHelper
				.findOneRecord(0, 1, "Scores.txt", ID, courseNum);
		if (resultString == null) {
			return null;
		} else {
			resultString = resultString.split(" ")[2];
		}
		return resultString;
	}

	public void displayPanel(ActionEvent e) {
		displayPanel.removeAll();
		System.out.println(operationButtons.indexOf(e.getSource()));
		displayPanel.add(operatingPanels.get(operationButtons.indexOf(e
				.getSource())));

		this.repaint();
	}

	public boolean hasRight(String courseNum, String ID) {
		String string = null;
		boolean hasRight = false;
		string = IOHelper.findOneRecord(0, 1, "courseSelected.txt", courseNum,
				this.ID);
		if (string != null) {
			hasRight = true;
		}
		return hasRight;
	}

	public String getNameFromFile() {
		Student student = new Student(this.ID);
		return student.getName();
	}

}
